﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Threading;
using System.Globalization;

namespace ProjectSem40701.Admin
{
    public partial class UserEdit : System.Web.UI.Page
    {
               
        Guid uid;
        private const string SUCCESS = "success";
        private const string FAIL = "fail";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
        }

        private void FillData()
        {
            try
            {
                string strUser = System.Web.HttpContext.Current.User.Identity.Name;
                string strUserID = Membership.GetUser(strUser).ProviderUserKey.ToString();
                Guid userID = new Guid(strUserID);

                //Fill UserName
                uid = new Guid(Request.QueryString["uid"].ToString());

                //Khong cho xoa chinh minh
                if (userID == uid)
                {
                    this.btnDelete.Enabled = false;
                }

                MembershipUser mu = Membership.GetUser(uid);
                this.lblUserName.Text = mu.UserName;

                AdminXSD.tbl_UserTableAdapters.tbl_User_Select_AllTableAdapter dp = 
                    new AdminXSD.tbl_UserTableAdapters.tbl_User_Select_AllTableAdapter();
                DataTable dttbl = dp.Get_tbl_User_Select_By_User_ID(uid);

                this.txtAddress.Text = dttbl.Rows[0]["UserAddress"].ToString();
                this.txtBirthDay.Text = Convert.ToDateTime(dttbl.Rows[0]["UserBirthDay"].ToString()).ToString("dd/MM/yyyy");
                this.txtDescription.Value = Server.HtmlDecode(dttbl.Rows[0]["UserDescription"].ToString());
                this.txtFName.Text = dttbl.Rows[0]["UserFirstName"].ToString();
                this.txtIDCard.Text = dttbl.Rows[0]["UserIDCard"].ToString();
                this.txtJob.Text = dttbl.Rows[0]["UserJob"].ToString();
                this.txtLName.Text = dttbl.Rows[0]["UserLastName"].ToString();
                this.txtPhone.Text = dttbl.Rows[0]["UserPhone"].ToString();

                foreach (ListItem item in this.cbbGender.Items)
                {
                    if (item.Value == dttbl.Rows[0]["UserGender"].ToString())
                    {
                        item.Selected = true;
                    }
                }

                foreach (ListItem item in this.cbbStatus.Items)
                {
                    if (item.Value == dttbl.Rows[0]["UserStatus"].ToString())
                    {
                        item.Selected = true;
                    }
                }
            }
            catch
            {
                //show error message here
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                //------------------Update Role----------------------//
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
                DateTime mydt = Convert.ToDateTime(this.txtBirthDay.Text);
                mydt = Convert.ToDateTime(mydt);

                uid = new Guid(Request.QueryString["uid"].ToString());
                MembershipUser mu = Membership.GetUser(uid);
                string userName = mu.UserName;
                string[] roles = Roles.GetRolesForUser(mu.UserName);
                int count = roles.Length;

                //neu ko co quyen nao thi insert them vao
                if (count < 1)
                {
                    Roles.AddUserToRole(userName, this.cbbRole.SelectedItem.Text.Trim());
                }
                //neu co thi remove het di roi add moi
                else
                {
                    Roles.RemoveUserFromRoles(userName, roles);
                    Roles.AddUserToRole(userName, this.cbbRole.SelectedItem.Text.Trim());
                }
                
                //-------------------Update info-----------------//
                AdminXSD.tbl_UserTableAdapters.tbl_User_Select_AllTableAdapter dp = new 
                    AdminXSD.tbl_UserTableAdapters.tbl_User_Select_AllTableAdapter();
                DataTable dttbl = dp.Get_tbl_User_Select_By_User_ID(uid);

                //neu chua co info thi add them vao
                if (dttbl.Rows.Count < 1)
                {
                    int ok = dp.tbl_User_Insert(uid, this.txtIDCard.Text.Trim(), this.txtFName.Text.Trim(),
                    this.txtLName.Text.Trim(), this.txtAddress.Text.Trim(), this.txtPhone.Text.Trim(),
                    this.txtJob.Text.Trim(), this.cbbGender.SelectedValue.Trim() == "1" ? true : false,
                    mydt, Server.HtmlEncode(this.txtDescription.Value.Trim()),
                    Convert.ToInt32(this.cbbStatus.SelectedValue.Trim()));

                    if (ok > 0)
                    {
                        Show_Dialog(SUCCESS);
                    }
                    else
                    {
                        Show_Dialog(FAIL);
                    }
                }
                //neu co roi thi update
                else
                {
                    int ok = dp.tbl_User_Update(uid, this.txtIDCard.Text.Trim(), this.txtFName.Text.Trim(),
                        this.txtLName.Text.Trim(), this.txtAddress.Text.Trim(), this.txtPhone.Text.Trim(),
                        this.txtJob.Text.Trim(), this.cbbGender.SelectedValue.Trim() == "1" ? true : false,
                        mydt, Server.HtmlEncode(this.txtDescription.Value.Trim()),
                        Convert.ToInt32(this.cbbStatus.SelectedValue.Trim()));

                    if (ok > 0)
                    {
                        Show_Dialog(SUCCESS);
                    }
                    else
                    {
                        Show_Dialog(FAIL);
                    }
                }
            }
            catch
            {
                //show error message here
                Show_Dialog(FAIL);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                //Chep, cho nay lien quan den nhieu bang thi met roi day
                AdminXSD.aspnet_UserTableAdapters.aspnet_UsersTableAdapter dp = new 
                    AdminXSD.aspnet_UserTableAdapters.aspnet_UsersTableAdapter();
                uid = new Guid(Request.QueryString["uid"].ToString());
                int ok = dp.aspnet_User_Delete_By_UserID(uid);
                
                if (ok > 0)
                {
                    //bao thanh cong
                    Show_Dialog_Del(SUCCESS);
                }
                else
                { 
                    //bao that bai
                    Show_Dialog_Del(FAIL);
                }
            }
            catch
            { 
                //Show error message here
                Show_Dialog_Del(FAIL);
            }

        }

        protected void cbbRole_DataBound(object sender, EventArgs e)
        {
            try
            {
                ListItem emptyItem = new ListItem();
                emptyItem.Value = "nothing";
                emptyItem.Text = "";
                this.cbbRole.Items.Add(emptyItem);

                uid = new Guid(Request.QueryString["uid"].ToString());
                MembershipUser mu = Membership.GetUser(uid);
                string selectedUsersRoles = "";

                if (Roles.GetRolesForUser(mu.UserName).Length > 0)
                {
                    selectedUsersRoles = Roles.GetRolesForUser(mu.UserName)[0];
                    foreach (ListItem item in this.cbbRole.Items)
                    {
                        if (item.Text == selectedUsersRoles)
                        {
                            item.Selected = true;
                        }
                    }
                }
                else
                {
                    emptyItem.Selected = true;
                }
            }
            catch
            {
                //Show message here
            }
        }

        /// <summary>
        /// Close dialog here
        /// </summary>
        private void Close_Dialog()
        {
            switch (this.lblSuccess.Text)
            {
                case SUCCESS:
                    Response.Redirect("User.aspx");
                    break;
                case FAIL:
                    this.btnUpdate_ModalPopupExtender.Enabled = false;
                    this.btnDelete_ModalPopupExtender.Enabled = false;
                    break;
                default:
                    this.btnUpdate_ModalPopupExtender.Enabled = false;
                    this.btnDelete_ModalPopupExtender.Enabled = false;
                    break;
            }
        }
        /// <summary>
        /// Show dialog trong trường hợp update
        /// </summary>
        private void Show_Dialog(String Check)
        {
            switch (Check)
            {
                case SUCCESS:
                    this.ltrMessage.Text = "Cập nhật thành công";
                    break;
                case FAIL:
                    this.ltrMessage.Text = "Cập nhật thất bại";
                    break;
                default:
                    this.ltrMessage.Text = "Lỗi không xác định, cập nhật thất bại";
                    break;
            }
            this.lblSuccess.Text = Check;
            this.btnUpdate_ModalPopupExtender.Enabled = true;
            this.btnUpdate_ModalPopupExtender.Show();
        }

        /// <summary>
        /// Show dialog trong trường hợp delete
        /// </summary>
        private void Show_Dialog_Del(String Check)
        {
            switch (Check)
            {
                case SUCCESS:
                    this.ltrMessage.Text = "Xóa thành công";
                    break;
                case FAIL:
                    this.ltrMessage.Text = "Xóa thất bại";
                    break;
                default:
                    this.ltrMessage.Text = "Lỗi không xác định, xóa thất bại";
                    break;
            }
            this.lblSuccess.Text = Check;
            this.btnDelete_ModalPopupExtender.Enabled = true;
            this.btnDelete_ModalPopupExtender.Show();
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            Close_Dialog();
        }

        protected void btnYes_Click(object sender, EventArgs e)
        {
            Close_Dialog();
        }
    }
}
